package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)
// 添加文章
func AddArtical(c *gin.Context) {

	var data model.Artical
	// 接收参数失败的情况
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": 500,
			"data":   "发送数据错误",
			"msg":    err.Error(),
		})
		return
	}
	code := model.CreateArtical(&data)

	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrorMsg(code),
	})

}
// todo 查询分类下所有文章的信息
func GetCateArt(c *gin.Context)  {
	/*
		接收pageSize 和pageNum
		使用 strconv.Atoi 转化为 int 类型
	*/
	var code int
	var data []model.Artical
	Cid, _ := strconv.Atoi(c.Query("Cid"))
	pageSize, pageSizeErr := strconv.Atoi(c.Query("pageSize"))
	pageNum, pageNumErr := strconv.Atoi(c.Query("pageNum"))
	if pageSizeErr != nil || pageNumErr != nil {
		code = errmsg.ERROR_PARMENTS
		data = nil
	} else {
		if pageSize == 0 {
			pageSize = -1
		}
		if pageNum == 0 {
			pageNum = -1
		}
		data, code = model.GetCateArt(Cid,pageSize,pageNum)

	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrorMsg(code),
	})
}
//  todo 查询单个文章的信息
func GetArtInfo(c *gin.Context) {
	/*
		接收 单篇文章的id即可
	 */
	var code int
	var artical  model.Artical
	id,idErr := strconv.Atoi(c.Query("id"))
	if idErr != nil {
		code = errmsg.ERROR_PARMENTS
		artical = artical
	} else {
		if id < 0 {
			id = 0
		}
	}
	artical,code = model.GetArtInfo(id)
	c.JSON(http.StatusOK,gin.H{
		"status": code,
		"data":   artical,
		"msg":    errmsg.GetErrorMsg(code),
	})


}

// todo 查询文章列表
func GetArticals(c *gin.Context) {

	/*
		接收pageSize 和pageNum
		使用 strconv.Atoi 转化为 int 类型
	*/
	var code int
	var data []model.Artical
	pageSize, pageSizeErr := strconv.Atoi(c.Query("pageSize"))
	pageNum, pageNumErr := strconv.Atoi(c.Query("pageNum"))
	if pageSizeErr != nil || pageNumErr != nil {
		code = errmsg.ERROR_PARMENTS
		data = nil
	} else {
		if pageSize == 0 {
			pageSize = -1
		}
		if pageNum == 0 {
			pageNum = -1
		}
		data, code = model.GetArticalList(pageSize,pageNum)

	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrorMsg(code),
	})

}

// 编辑分类
func EditArtical(c *gin.Context) {
	var data model.Artical
	c.ShouldBindJSON(&data)
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.EditArtical(id,&data)

	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrorMsg(code),
	})

}

// 删除分类
func DeleteArtical(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteArtical(id)
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrorMsg(code),
	})

}
